// 第1行附近添加：
const newsData = require('../../utils/newsData.js');  // 引入新闻数据模块

Page({
  data: {
    stockData: {}, // 存储股票数据的变量
    chartImage: 'http://image.sinajs.cn/newchart/min/n/sz300819.gif', // 默认显示日k线图
    currentTab: 0,
    pageCur: '',
    newsList: [{
        id: 1,
        title: "渤海汽车：渤海汽车2024年年度报告摘要",
        source: "交易所公告",
        time: "00:07",
        content: "这里是渤海汽车2024年年度报告摘要的详细内容..."
      },
      {
        id: 2,
        title: "渤海汽车：渤海汽车关于召开2024年度暨2025年第一季度业绩说明会的公告",
        source: "上交所股票",
        time: "00:02",
        content: "这里是业绩说明会公告的详细内容..."
      },
      {
        id: 3,
        title: "图解渤海汽车年报：第四季度单季净利润同比减1066.45%",
        source: "证券之星",
        time: "00:43",
        content: "这里是年报图解的详细内容..."
      },
      {
        id: 4,
        title: "渤海汽车：渤海汽车关于2024年度计提信用与资产减值准备的公告",
        source: "上交所股票",
        time: "00:03",
        content: "这里是资产减值准备公告的详细内容..."
      }
    ],// 添加新闻数据
    lastNewsId: '', // 用于滚动到最后一条新闻

    openid: '',
    isLogin: false,
    selectedStocks: [],
    isSelected: false,
    stockCode: '',  // 当前股票代码
  },

  triggerShare() {
    wx.showShareMenu({
      withShareTicket: true
    });
    wx.showToast({
      title: '请点击右上角进行分享',
      icon: 'none'
    });
  },

  // 保留 onShareAppMessage
  onShareAppMessage() {
    return {
      title: `${this.data.stockName}（${this.data.stockCode}）`,
      path: `/pages/stock/stock?name=${encodeURIComponent(this.data.stockName)}&code=${this.data.stockCode}`,

      imageUrl: this.data.chartImage
    };
  },

  navigateToNewsDetail: function (e) {
    const newsId = e.currentTarget.dataset.id;
    const stockCode = this.data.stockCode;
    wx.navigateTo({
      url: `/pages/newsDetail/newsDetail?code=${stockCode}&id=${newsId}`
    });
  },

  // 新增方法：跳转到新闻详情
  switchChart: function(event) {
    const chartType = event.currentTarget.dataset.chart;
    const currentTab = event.currentTarget.dataset.current;
    const code = this.data.stockCode.toLowerCase(); // 获取当前股票代码
    
    let chartImage = '';
    switch (chartType) {
        case '分时':
            chartImage = `http://image.sinajs.cn/newchart/min/n/${code}.gif`;
            break;
        case '日k':
            chartImage = `http://image.sinajs.cn/newchart/daily/n/${code}.gif`;
            break;
        case '周k':
            chartImage = `http://image.sinajs.cn/newchart/weekly/n/${code}.gif`;
            break;
        case '月k':
            chartImage = `http://image.sinajs.cn/newchart/monthly/n/${code}.gif`;
            break;
        default:
            break;
    }
    
    this.setData({
        chartImage: chartImage,
        currentTab: currentTab
    });
  },

  loadStockData(stockCode) {
    let _this = this;
    wx.request({
        url: 'https://hq.sinajs.cn/',
        data: {
            list: stockCode.toLowerCase() // 使用传入的股票代码
        },
        success(res) {
            // 数据处理逻辑保持不变
            let dataArr = res.data.split(',');
            let stockData = {
              name: dataArr[0], // 股票名称
              todayOpen: dataArr[1], // 今日开盘价
              yesterdayClose: dataArr[2], // 昨日收盘价
              currentPrice: dataArr[3], // 当前价格
              todayHighest: dataArr[4], // 今日最高价
              todayLowest: dataArr[5], // 今日最低价
              buyPrice: dataArr[6], // 竞买价，买一报价
              sellPrice: dataArr[7], // 竞卖价，卖一报价
              tradedStocks: Math.round(dataArr[8] / 100), // 成交股票数（除以100得手数）
              tradedAmount: Math.round(dataArr[9] / 10000), // 成交金额（除以10000得万元）
              buy1Quantity: dataArr[10], // 买一申请股数
              buy1Price: dataArr[11], // 买一报价
              buy2Quantity: dataArr[12], // 买二申请股数
              buy2Price: dataArr[13], // 买二报价
              buy3Quantity: dataArr[14], // 买三申请股数
              buy3Price: dataArr[15], // 买三报价
              buy4Quantity: dataArr[16], // 买四申请股数
              buy4Price: dataArr[17], // 买四报价
              buy5Quantity: dataArr[18], // 买五申请股数
              buy5Price: dataArr[19], // 买五报价
              sell1Quantity: dataArr[20], // 卖一申请股数
              sell1Price: dataArr[21], // 卖一报价
              sell2Quantity: dataArr[22], // 卖二申请股数
              sell2Price: dataArr[23], // 卖二报价
              sell3Quantity: dataArr[24], // 卖三申请股数
              sell3Price: dataArr[25], // 卖三报价
              sell4Quantity: dataArr[26], // 卖四申请股数
              sell4Price: dataArr[27], // 卖四报价
              sell5Quantity: dataArr[28], // 卖五申请股数
              sell5Price: dataArr[29], // 卖五报价
              date: dataArr[30], // 日期
              time: dataArr[31] // 时间
            };
            // 计算换手率等数据
            let circulatingShares = 951000000; //拟定流通股本
            let riseFallPrice = (stockData.currentPrice - stockData.yesterdayClose).toFixed(2);
            let riseFallRate = ((stockData.currentPrice - stockData.yesterdayClose) / stockData.yesterdayClose * 100).toFixed(1);
            let tradedStocks_new = (stockData.tradedStocks / 10000).toFixed(1);
            let todayHighest = parseFloat(stockData.todayHighest);
            let todayOpen = parseFloat(stockData.todayOpen);
            let currentPrice = parseFloat(stockData.currentPrice);
            let todayLowest = parseFloat(stockData.todayLowest);
            let tradedAmount = parseFloat(stockData.tradedAmount);
            let buy1Quantity = parseFloat(stockData.buy1Quantity);
            let buy2Quantity = parseFloat(stockData.buy2Quantity);
            let buy3Quantity = parseFloat(stockData.buy3Quantity);
            let buy4Quantity = parseFloat(stockData.buy4Quantity);
            let buy5Quantity = parseFloat(stockData.buy5Quantity);
            let buy1Price = parseFloat(stockData.buy1Price);
            let buy2Price = parseFloat(stockData.buy2Price);
            let buy3Price = parseFloat(stockData.buy3Price);
            let buy4Price = parseFloat(stockData.buy4Price);
            let buy5Price = parseFloat(stockData.buy5Price);
            let sell1Quantity = parseFloat(stockData.sell1Quantity);
            let sell2Quantity = parseFloat(stockData.sell2Quantity);
            let sell3Quantity = parseFloat(stockData.sell3Quantity);
            let sell4Quantity = parseFloat(stockData.sell4Quantity);
            let sell5Quantity = parseFloat(stockData.sell5Quantity);
            let sell1Price = parseFloat(stockData.sell1Price);
            let sell2Price = parseFloat(stockData.sell2Price);
            let sell3Price = parseFloat(stockData.sell3Price);
            let sell4Price = parseFloat(stockData.sell4Price);
            let sell5Price = parseFloat(stockData.sell5Price);
            let turnoverRate = (stockData.tradedStocks / circulatingShares * 10000).toFixed(2);
            // ✅ 获取该股票对应的模拟新闻
            let news = newsData.getNewsByCode(stockCode);

            // 更新数据
            _this.setData({
              stockData: stockData,
              riseFallPrice: riseFallPrice,
              riseFallRate: riseFallRate,
              tradedStocks_new: tradedStocks_new,
              todayHighest: todayHighest.toFixed(2),
              todayOpen: todayOpen.toFixed(2),
              currentPrice: currentPrice.toFixed(2),
              todayLowest: todayLowest.toFixed(2),
              tradedAmount: (tradedAmount / 10000).toFixed(1),
              buy1Quantity: (buy1Quantity / 100).toFixed(0),
              buy2Quantity: (buy2Quantity / 100).toFixed(0),
              buy3Quantity: (buy3Quantity / 100).toFixed(0),
              buy4Quantity: (buy4Quantity / 100).toFixed(0),
              buy5Quantity: (buy5Quantity / 100).toFixed(0),
              buy1Price: buy1Price.toFixed(2),
              buy2Price: buy2Price.toFixed(2),
              buy3Price: buy3Price.toFixed(2),
              buy4Price: buy4Price.toFixed(2),
              buy5Price: buy5Price.toFixed(2),
              sell1Quantity: (sell1Quantity / 100).toFixed(0),
              sell2Quantity: (sell2Quantity / 100).toFixed(0),
              sell3Quantity: (sell3Quantity / 100).toFixed(0),
              sell4Quantity: (sell4Quantity / 100).toFixed(0),
              sell5Quantity: (sell5Quantity / 100).toFixed(0),
              sell1Price: sell1Price.toFixed(2),
              sell2Price: sell2Price.toFixed(2),
              sell3Price: sell3Price.toFixed(2),
              sell4Price: sell4Price.toFixed(2),
              sell5Price: sell5Price.toFixed(2),
              turnoverRate: turnoverRate + '%',
              newsList: news, // ✅ 添加新闻列表
              lastNewsId: news.length > 0 ? 'news' + news[news.length - 1].id : '' // ✅ 用于滚动定位
            });
        }
    });
  },

  async onLoad(options) {
    // 设置定时器，每5秒刷新一次数据
    this.refreshInterval = setInterval(() => {
      this.loadStockData(this.data.stockCode);
    }, 5000);

    //const newsCount = this.data.newsList.length;//设置最后一条新闻的ID，用于自动滚动
    if (newsCount > 0) {
      this.setData({
        lastNewsId: 'news' + this.data.newsList[newsCount - 1].id
      });
    }

    // 从URL参数中获取name和code
    const name = options.name ? decodeURIComponent(options.name) : '未知股票';
    const code = options.code || '000000';

    // 设置导航栏标题
    wx.setNavigationBarTitle({
      title: `${name}（${code}）`,
    });
    // 这里可以继续获取该股票的详细信息
    this.setData({
      stockName: name,
      stockCode: code
    });
    // 根据股票代码生成对应的图表URL前缀
    const chartPrefix = `http://image.sinajs.cn/newchart/min/n/${code.toLowerCase()}`;
    this.setData({
      chartImage: `${chartPrefix}.gif`, // 默认显示分时图
    });
    this.loadStockData(code); // 调用加载股票数据的方法

    // 一定要等待登录状态完成再执行后续
    // 修改位置：stock.js 的 onLoad 中间位置（大概 240 行左右）
    // ✅ 修改后的写法
    await this.checkLoginStatus();  // 等待 openid 获取完毕
    if (this.data.isLogin) {
      await this.loadSelectedStocks();
      this.updateIsSelected();
    }

    // 设置新闻滚动id
    const newsCount = this.data.newsList.length;
    if (newsCount > 0) {
      this.setData({
        lastNewsId: 'news' + this.data.newsList[newsCount - 1].id
      });
    }

    // 设置定时刷新
    this.refreshInterval = setInterval(() => {
      this.loadStockData(this.data.stockCode);
    }, 5000);
  },

  onReady() {},
  onShow() {},
  onHide() {},
  onUnload() {
    // 清除定时器
    if (this.refreshInterval) {
      clearInterval(this.refreshInterval);
    }
  },

  // ===== 新增函数：检查登录状态并获取openid =====
  checkLoginStatus() {
    return new Promise((resolve, reject) => {
      wx.cloud.callFunction({
        name: 'getOpenId',
        success: async res => {
          const openid = res.result?.openid || '';
          console.log('【获取 openid】=>', openid);

          const db = wx.cloud.database();

          let isLogin = false;
          try {
            const userRes = await db.collection('user').where({ openid }).get();
            isLogin = userRes.data.length > 0 && userRes.data[0].isLogin === true;
          } catch (e) {
            console.error('检查登录状态失败:', e);
          }

          this.setData({
            openid,
            isLogin
          }, () => {
            console.log('【设置 isLogin】=>', isLogin);
            resolve();
          });
        },
        fail: err => {
          console.error('getOpenId 失败:', err);
          this.setData({
            openid: '',
            isLogin: false
          }, () => resolve());
        }
      });
    });
  },

  // ===== 新增函数：加载用户自选股列表 =====
  loadSelectedStocks: async function () {
    if (!this.data.isLogin) return;

    const db = wx.cloud.database();
    try {
      const res = await db.collection('selectedStock').where({ openid: this.data.openid }).get();
      if (res.data.length > 0) {
        this.setData({
          selectedStocks: res.data[0].stocks || []
        });
      } else {
        this.setData({ selectedStocks: [] });
      }
    } catch (err) {
      console.error('加载自选股失败', err);
      this.setData({ selectedStocks: [] });
    }
  },

  // ===== 新增函数：更新当前股票是否已自选 =====
  updateIsSelected() {
    const isSelected = this.data.selectedStocks.includes(this.data.stockCode);
    this.setData({ isSelected });
  },

  // ===== 修改后的 toggleSelected：实时验证是否登录 =====
  async toggleSelected() {
    // ✅ 每次点击按钮时都调用 checkLoginStatus
    await this.checkLoginStatus();  // 等待 openid 获取

    if (!this.data.isLogin) {
      // ✅ 若未登录则跳转到登录页
      wx.showToast({ title: '请先登录', icon: 'none' });
      wx.navigateTo({
        url: '/pages/login/login'
      });
      return;
    }

    // ✅ 已登录才执行添加/删除逻辑
    const db = wx.cloud.database();
    const openid = this.data.openid;
    const stockCode = this.data.stockCode;

    try {
      const res = await db.collection('selectedStock').where({ openid }).get();

      if (res.data.length === 0) {
        // 没有记录，创建一条
        await db.collection('selectedStock').add({
          data: {
            openid,
            stocks: [stockCode]
          }
        });
      } else {
        // 有记录，更新
        let stocks = res.data[0].stocks || [];
        if (this.data.isSelected) {
          stocks = stocks.filter(code => code !== stockCode);
        } else {
          if (!stocks.includes(stockCode)) {
            stocks.push(stockCode);
          }
        }
        await db.collection('selectedStock').doc(res.data[0]._id).update({
          data: { stocks: stocks }
        });
      }

      await this.loadSelectedStocks();
      this.updateIsSelected();
    } catch (err) {
      console.error('更新自选股失败', err);
      wx.showToast({ title: '操作失败', icon: 'error' });
    }
  },

  // ========== 新增：模拟交易跳转 ==========
  goToTrade() {
    wx.navigateTo({
      url: `/pages/trade/trade?code=${this.data.stockCode}&name=${encodeURIComponent(this.data.stockName)}&price=${this.data.currentPrice || this.data.stockData.currentPrice || 0}`
    });
  },

  //页面相关事件处理函数--监听用户下拉动作
  onPullDownRefresh() {},
  //页面上拉触底事件的处理函数
  onReachBottom() {},
  //用户点击右上角分享
  onShareAppMessage: function() {
    return {
        title: `${this.data.stockName}（${this.data.stockCode}）`,
        path: `/pages/stock/stock?name=${encodeURIComponent(this.data.stockName)}&code=${this.data.stockCode}`,
        imageUrl: this.data.chartImage
    }
  },
});
